package isquirrel.servlets;

import isquirrel.Logger;
import isquirrel.QueuePool;
import isquirrel.beans.Interest;
import isquirrel.beans.User;
import isquirrel.beans.UserInterest;
import isquirrel.error.CannotLoginUserException;
import isquirrel.semantic.DBpedia;
import isquirrel.servlets.handler.HttpDBServlet;
import isquirrel.util.HibernateUtil;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletException;

import org.json.JSONException;
import org.json.JSONObject;

public class AddInterest extends HttpDBServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Interest newInterest;
	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException {
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void handlePost() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		String label = request.getParameter("interest");
		User user = getLoggedInUser();
		DBpedia dbPedia = new DBpedia();
		Set<String> subjects = dbPedia.getSubjects(label);
		
		JSONObject jsonResponse = new JSONObject();

		if (subjects.isEmpty()) {
			jsonResponse.put("error",1);
			jsonResponse.put("msg","A quick search showed no results for this. Try rephrasing your interest.");
			writeAjaxResponse(jsonResponse);
		}
		else{
			//Add new interest
			newInterest = new Interest(label, subjects);
			if (!user.getInterests().contains(newInterest)) {
				user.addInterest(newInterest);
				HibernateUtil.getSession().saveOrUpdate(user);
				jsonResponse.put("error",0);
				jsonResponse.put("msg","Added in queue. Recommendations for <i>'" + newInterest.getLabel() + "'</i> should appear soon." );
				Logger.log(user, "added interest");
//				System.out.println("About to add");
				QueuePool.getQueue("rec").add(new UserInterest(user,newInterest));
				writeAjaxResponse(jsonResponse);
			}
			else{
				jsonResponse.put("error",1);
				jsonResponse.put("msg","You have already added this interest.");
				writeAjaxResponse(jsonResponse);
			}
		}
		
	}					

	

}
